package com.ruoyi.project.zxbd.service.impl;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.zx.PageData;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.zxbd.mapper.LeaveapplyMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional
public class LeaveApplyServiceImpl extends BaseController {
    @Autowired
    private LeaveapplyMapper leaveapplyMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    /**
     * IdentityService 是一个用于管理用户和组的服务
     * 它提供了一组 API，可以创建、查询、更新和删除Activiti引擎中的用户和组，以及管理这些用户和组之间的关系
     */
    @Resource
    private IdentityService identityService;

    /**
     *查询请假
     * @param id:请假主键
     * @return 请假
     */
    public PageData selectLeaveApplyById(Long id){
        return leaveapplyMapper.selectLeaveapplyById(id);
    }
    /**
     * 查询请假：用于待办事件回写请假信息
     * @param name:请假人
     * @return 请假
     */
    public PageData selectLeaveApplyByName(String name){
        return leaveapplyMapper.selectLeaveapplyByName(name);
    }
    /**
     * 查询请假列表
     *
     * @param leaveapply 请假
     * @return 请假
     */
    public List<PageData> selectLeaveApplyList(PageData leaveapply){
        return leaveapplyMapper.selectLeaveapplyList(leaveapply);
    }

    /**
     * 新增请假：发起一个请假流程后，自动完成请假申请
     *
     * @param pageData 请假
     * @return 结果
     */
    public int insertLeaveApply(PageData pageData){
        int rows = leaveapplyMapper.insertLeaveapply(pageData);
        // 下面是发起一个请假流程，需要通过runtimeService来实现
        identityService.setAuthenticatedUserId((String) pageData.get("user_id"));//设置流程实例的发起人
        HashMap<String, Object> variables = new HashMap<>();
        //这里的字段applyuserid，deptleader在bpmn文件中定义好的，如要修改要提前在bpmn文件对应修改
        variables.put("applyuserid", pageData.get("user_id"));
        variables.put("deptleader", pageData.get("dept_leader"));
        //启动一个流程实例:"leave"流程定义的key,id作为业务关联键
        //启动一个流程后，在对应的act_ru_task表中就会存在一条记录
        runtimeService.startProcessInstanceByKey("leave", String.valueOf(pageData.get("id")), variables);
        // 自动完成第一个任务
        Task autoTask = taskService.createTaskQuery()
                .processDefinitionKey("leave")
                .processInstanceBusinessKey(String.valueOf(pageData.get("id")))
                .singleResult();
        taskService.complete(autoTask.getId());
        return rows;
    }

    /**
     * 修改请假
     *
     * @param leaveapply 请假
     * @return 结果
     */
    public int updateLeaveApply(PageData leaveapply) {
        return leaveapplyMapper.updateLeaveapply(leaveapply);
    }

    /**
     * 批量删除请假
     *
     * @param ids 需要删除的请假主键
     * @return 结果
     */
    public int deleteLeaveApplyByIds(String ids) {
        String[] keys = Convert.toStrArray(ids);
        for (String key : keys) {
            ProcessInstance process =
                    runtimeService.createProcessInstanceQuery()
                            .processDefinitionKey("leave")
                            .processInstanceBusinessKey(key)
                            .singleResult();
            if (process != null) {
                runtimeService.deleteProcessInstance(process.getId(), "删除");
            }
            // 删除历史数据
            HistoricProcessInstance history =
                    historyService.createHistoricProcessInstanceQuery()
                            .processDefinitionKey("leave")
                            .processInstanceBusinessKey(key)
                            .singleResult();
            if (history != null){
                historyService.deleteHistoricProcessInstance(history.getId());
            }
            leaveapplyMapper.deleteLeaveapplyById(Long.parseLong(key));
        }
        return keys.length;
    }

    /**
     * 删除请假信息
     *
     * @param id 请假主键
     * @return 结果
     */
    public int deleteLeaveApplyById(Long id) {
        return leaveapplyMapper.deleteLeaveapplyById(id);
    }


}
